<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | ProjectName: mvc
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.xfjpeter.cn
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 201907162019-07-16
 * | ---------------------------------------------------------------------------------------------------
 * | Desc:
 * | ---------------------------------------------------------------------------------------------------
 */

namespace app\admin\behavior;

use think\Container;
use think\facade\Route;

class Router
{
    public function appInit($params)
    {
        // 加载路由
        $this->loadRouter();

        // 判断是否测试模式，拦截路由
        $this->interceptRequest();
    }

    /**
     * 加载路由
     */
    private function loadRouter()
    {
        Route::group('admin', function () {
            Route::get('/test$', function () {
                return json(['code' => 0, 'msg' => 'if you see this, then router is ok.']);
            });
            // 查询数据库中的规则路由
            $rules = db('rule')->where(['status' => 1])->select();
            foreach ($rules as $rule) {
                $route = $rule['module'] . '/' . $rule['controller'] . '/' . $rule['action'];
                Route::rule($rule['router'], $route, $rule['method']);
            }
        })
            ->middleware(['Auth'])
            ->allowCrossDomain();
    }

    /**
     * 测试模式拦截请求
     */
    private function interceptRequest()
    {
        $request = Container::getInstance()->request;
        if (config('johnxu.mode_test') && ($request->isAjax() || $request->isPost() || $request->isDelete())) {
            if ($request->server('REQUEST_URI') != '/admin/login') {
                echo json_encode(['err_code' => -1, 'message' => '测试模式不允许操作数据'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                exit();
            }
        }
    }
}